//
//  ViewController.swift
//  Youtube2
//
//  Created by 劢克科技 on 2019/4/30.
//  Copyright © 2019 meckey. All rights reserved.
//

import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // 单元格ID
    let cellIdentifier = "cellIdentifier"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置集合背景色
        collectionView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        // 注册单元格
        collectionView.register(VideoCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
        // 将导航条设置为非透明
        navigationController?.navigationBar.isTranslucent = false
        
        // 自定义导航标题样式
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0))
        titleLabel.text = "Home"
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        titleLabel.textColor = UIColor.white
        navigationItem.titleView = titleLabel
        
        // 设置collectionView内容的内边距，设置滚动条的内边距
        collectionView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
        collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
        
        // 添加状态栏
        setupMenuBar()
        // 添加按钮
        setupNavBtns()
        // 添加数据
        setupData()
    }
    
    // 请求数据
    fileprivate func setupData() {
        
        let jsonUrl = URL(string: "https://s3-us-west-2.amazonaws.com/youtubeassets/home.json")
        URLSession.shared.dataTask(with: jsonUrl!) { (data, response, err) in
            
            // 错误处理
            if err != nil {
                print(err as Any)
                return
            }
            
            do {
                // 处理返回的Json
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                guard let jsonDict = json as? [[String: Any]] else {
                    print("Json to Dictionary error.")
                    return
                }
                
                for item in jsonDict {
                    let title = item["title"] as! String
                    let thumb = item["thumbnail_image_name"] as! String
                    let chanel = item["channel"] as! [String: Any]
                    let avatar = chanel["profile_image_name"] as! String
                    let desc = "\(chanel["name"] as! String) · \(item["number_of_views"] as! Int) views · 2 years ago"
                    let model = VideosModel(title: title, desc: desc, thumb: thumb, avatar: avatar)
                    self.videos.append(model)
                }
                
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            } catch let jsonErr {
                print(jsonErr)
            }

        }.resume()
    }
    
    //MARK: - Getter
    
    lazy var menuBar: MenuBar = {
        let view = MenuBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        return view
    }()
    
    lazy var settingLaunch: SettingLaunch = {
        let view = SettingLaunch()
        view.delegate = self
        return view
    }()

    //MARK: - Setter
    
    var videos = [VideosModel]()
    
    //MARK: - DataSource
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return videos.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! VideoCell
        cell.video = videos[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height = (view.frame.width - 10 - 10) * 9 / 16
        return CGSize(width: UIScreen.main.bounds.width, height: height + 84)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

//MARK: - Setting Delegate

extension ViewController: SettingLaunchDelegate {
    
    func handleDismiss(setting: String) {
        let controller = UIViewController()
        controller.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        controller.title = setting
        
        navigationController?.navigationBar.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        navigationController?.pushViewController(controller, animated: true)
    }
}

//MARK: - UI

extension ViewController {
    // 导航栏右侧按钮
    fileprivate func setupNavBtns() {
        let searchImage = #imageLiteral(resourceName: "sousuo").withRenderingMode(.alwaysOriginal)
        let searchBtn = UIBarButtonItem(image: searchImage, style: .plain, target: nil, action: nil)
        
        let moreImage = #imageLiteral(resourceName: "gengduo").withRenderingMode(.alwaysOriginal)
        let moreBtn = UIBarButtonItem(image: moreImage, style: .plain, target: self, action: #selector(handleMore))
        
        self.navigationItem.rightBarButtonItems = [moreBtn, searchBtn]
    }
    
    // 点击导航右侧按钮
    @objc fileprivate func handleMore() {
        settingLaunch.showLaunch()
    }
    
    // 设置自定义四个按钮导航
    fileprivate func setupMenuBar() {
        view.addSubview(menuBar)
    }
}
